<?php
if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOOPS_MODULE_PATH. '/scuttle/class/AbstractViewAction.class.php';
require_once XOOPS_MODULE_PATH. '/scuttle/forms/SearchForm.class.php';
require_once XOOPS_MODULE_PATH. '/scuttle/include/TagService.php';
require_once XOOPS_MODULE_PATH. '/scuttle/include/functions.php';
require_once XOOPS_ROOT_PATH . "/core/XCube_PageNavigator.class.php";

class Scuttle_SearchAction extends Scuttle_AbstractViewAction
{
	var $resultArray = array();

	var $queryWords = null;
	var $mPagenavi = null;
	var $perPage = 20;    // page count
	var $getUserId = 0;
	var $moduleHeader = null;
	var $confirmMssage = null;
	var $errorMssage  = null;
	var $prettyPhoto = false;    // use prettyPhoto

	function _getQuery()
	{
		return xoops_getrequest('query');
	}

	function _getStatus()
	{
		return xoops_getrequest('status');
	}

	function _getStart()
	{
		return xoops_getrequest('start');
	}

	function &_getHandler()
	{
		$handler =& xoops_getmodulehandler('bookmarks');
		return $handler;
	}

	function _getBaseUrl()
	{
		return 'index.php?action=Search';
	}

	function &_getPageNavi()
	{
		$navi =& new XCube_PageNavigator($this->_getBaseUrl(), XCUBE_PAGENAVI_START);
		$navi->setStart($this->_getStart());
		$navi->setPerpage($this->perPage);
		$navi->setTotalItems($this->totalCount);
		$navi->addExtra('query', trim($this->_getQuery()));
		if ($this->getUserId > 0) {
			// add pagenavi parameter
			$navi->addExtra('uid', $this->getUserId);
		}
		return $navi;
	}


	function &_getFilterForm()
	{
		$filter =& new Scuttle_DBFilterForm($this->_getPageNavi(), $this->_getHandler());
		return $filter;
	}


	function prepare(&$controller, &$xoopsUser, $moduleConfig)
	{
		$this->mConfig = $moduleConfig;
	}

	function getDefaultView(&$controller, &$xoopsUser)
	{
		// function local
		$userId = null;
		$uid = null;
		$retArray = array();
		$startEntry = $this->_getStart() ;
		$getStatus = $this->_getStatus();

		$root =& XCube_Root::getSingleton();
		$db =& $root->mController->mDB;

		$this->queryWords = trim($this->_getQuery());

		if ($this->queryWords == '') {
			// no query word
			$this->errorMssage = _MD_SC_NOWORD;
		} else {
			$handler =& $this->_getHandler();
			$tagHandler = xoops_getmodulehandler('tags');

			// check user and userid
			if (is_object($xoopsUser)) {
				$userId = $root->mContext->mXoopsUser->get('uid');
				if ($getStatus == 0) {
					// users bookmarks
					$statusSql = ' ( bStatus < 2 OR  uId ='. $userId. ')';
				} elseif ($getStatus == 1) {
					// users bookmarks
					$statusSql = ' uId ='. $userId;
				} elseif ($getStatus == 2) {
					// users watchlist
					$statusSql = ' bStatus = 2 AND uId ='. $userId;
				}
			} else {
				// guest user
				if ($getStatus == 0) {
					// bookmarks
					$statusSql = ' ( bStatus < 2 )';
				} elseif ($getStatus == 1) {
					// watchlist
					 $statusSql = ' bStatus < 2';
				}
			}

			// Array to Search words with space
			$queryArray = preg_split ("/[\s,]+/", $this->queryWords); 
			$sql = "SELECT bId, uId, bStatus, bModified, bTitle, bAddress, bDescription, image FROM ". $db->prefix("scuttle_bookmarks"). " WHERE". $statusSql;
			if (is_array($queryArray) && $count = count($queryArray)) {
				// Full text search
				$sql .= " AND ((bTitle       LIKE '%$queryArray[0]%' OR 
						bAddress     LIKE '%$queryArray[0]%' OR 
						bDescription LIKE '%$queryArray[0]%')";
						for($i = 1;$i < $count;$i++) {
							$sql .= " AND ";
							$sql .= "(bTitle     LIKE '%$queryArray[$i]%' OR 
								bAddress     LIKE '%$queryArray[$i]%' OR 
								bDescription LIKE '%$queryArray[$i]%')";
						}
				$sql .= ") ";
			} 
			$sql .= " ORDER BY bModified DESC";
			$result = $db->query($sql);
			$this->totalCount = $db->getRowsNum($result);
			if ($this->totalCount >0) {
				$result = $db->query($sql, $this->perPage, $startEntry);
				while (list($bId, $uId, $bStatus, $bModified, $bTitle, $bAddress, $bDescription, $image) = $db->fetchRow($result)) {
					array_push($retArray, array(
						'bId'  => $bId,
						'uId' => $uId,
						'bStatus' => $bStatus,
						'bModified' => $bModified,
						'bTitle' => $bTitle,
						'bAddress'  => $bAddress,
						'bDescription' => $bDescription,
						'hatena' => addHatenaUsers($bAddress),    // hatena bookmark
						'tag_array' => $tagHandler->getEntoryTagArray($bId),
						'image' => $image,
					));
				}
				$this->resultArray = $retArray;
				$this->prettyPhoto = true;
			} else {
				// result words is non
				$this->errorMssage = _MD_SC_NOTRESULT;
			}
		}

		// Page navi
		if ($this->totalCount > $this->perPage ) {
			$this->mPagenavi =$this->_getPageNavi();
			$this->mPagenavi->fetch();
		}

		$this->breadcrumbs[] = array('name' => $root->mContext->mModule->mXoopsModule->getVar('name'), 'url' => 'index.php' ) ;
		if ($this->queryWords <> '') {
			$this->breadcrumbs[] = array('name' => htmlSpecialChars($this->queryWords, ENT_QUOTES )) ;
		}
		$this->pageTitle = $root->mContext->mModule->mXoopsModule->getVar('name') .' &raquo; '. _MD_SC_SEARCHRESULTS;
		$this->moduleHeader.= "<script type=\"text/javascript\" src=\"" . XOOPS_URL ."/modules/scuttle/js/jsDelete.php\"></script>\n";
		// use prettyPhoto
		if ($this->prettyPhoto) {
			$this->moduleHeader.= "<script type=\"text/javascript\" src=\"" . XOOPS_URL ."/common/js/jQuery/jquery.js\"></script>\n";
			$this->moduleHeader.= "<script type=\"text/javascript\" src=\"" . XOOPS_URL ."/common/js/jQuery/prettyPhoto/jquery.prettyPhoto.js\"></script>\n";
			$this->moduleHeader.= "<link rel=\"stylesheet\" type=\"text/css\" media=\"projection, screen\" href=\"" .  XOOPS_URL ."/common/js/jQuery/prettyPhoto/css/prettyPhoto.css\" />\n";
		}
		$this->moduleHeader.= '<link rel="stylesheet" type="text/css" href="' . XOOPS_MODULE_URL. '/scuttle/module.css" />'."\n";

		return SC_FRAME_VIEW_INDEX;
	}

	function executeViewIndex(&$controller, &$xoopsUser, &$render)
	{
		$render->setTemplateName('scuttle_search.html');
		$render->setAttribute('querywords' ,$this->queryWords);
		$render->setAttribute('result_array' ,$this->resultArray);
		$render->setAttribute('status'   , $this->_getStatus());
		$render->setAttribute('total_count' , $this->totalCount);
		$render->setAttribute('pageNavi'   , $this->mPagenavi);
		$render->setAttribute('pretty_photo'  , $this->prettyPhoto);
		$render->setAttribute('confirm_mssage', $this->confirmMssage);
		$render->setAttribute('error_mssage', $this->errorMssage);
		$render->setAttribute('xoops_pagetitle'  , $this->pageTitle );
		$render->setAttribute('xoops_breadcrumbs'  ,$this->breadcrumbs) ;
		$render->setAttribute('xoops_module_header',$this->moduleHeader);
		if (is_object($xoopsUser)) {
			$render->setAttribute('rangeOptions', array("0" => _MD_SC_BOOKMARKS_RANGE_0, "1" => _MD_SC_BOOKMARKS_RANGE_1, "2" => _MD_SC_BOOKMARKS_RANGE_2));
		} else {
			$render->setAttribute('rangeOptions', array("0" => _MD_SC_BOOKMARKS_GUESTRANGE_0, "1" => _MD_SC_BOOKMARKS_GUESTRANGE_1));
		}
	}

	function executeViewError(&$controller, &$xoopsUser, &$render)
	{
		$url = 'index.php';
		$controller->executeRedirect($url, 1, _MD_SC_ERORR_NOSUBMITTED);
	}

}
?>
